<template>
  <section>
    <!-- 面包屑 -->
      <breadcrumbs></breadcrumbs>
    <!-- <btns @exec="exec"></btns> -->
    <div class="data-container scroll-table">
      <div>
        <el-button @click="showCourseContentForm(1)">新增</el-button>
        <!-- <el-button @click="showCourseContentForm(2)">编辑</el-button> -->
        <el-button @click="del">删除</el-button>
      </div>
      <div class="flex">
        <div class="ind-title lh50 f16">课程关联列表</div>
        <el-button type="primary" @click="returnCourseList">返回课程管理列表</el-button>
      </div>
      <el-table :data="tableData" @selection-change="tableSelectionChange" style="width: 100%" row-key="ifId" border lazy>
        <el-table-column type="selection" width="55"></el-table-column>
        <el-table-column label="序号" prop="index" type="index" width="100px"></el-table-column>
        <el-table-column prop="title" label="标题" align="center"> </el-table-column>
        <el-table-column prop="" label="封面" width="150" align="center">
          <template slot-scope="scope">
            <img :src="scope.row.headImg" alt="" class="img-feng">
          </template>
        </el-table-column>
        <el-table-column label="名师名称" prop="teachName"></el-table-column>
      </el-table>
      <!-- <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="currentPage" :page-sizes="[5, 10, 15, 20]"
                     :page-size="pageSize" layout="total, sizes, prev, pager, next, jumper" :total="total">
      </el-pagination> -->
    </div>
    <el-dialog title="课程关联信息" :visible.sync="dialogCreateFormVisible">
      <el-form :model="createForm" label-width="120px" ref="createForm" :rules="rules">
          <el-form-item label="选择关联课程" prop="outCourseId">
          <!-- :remote-method="remoteMethod"  :loading="loading" -->
                    <el-select v-model="createForm.outCourseId" multiple filterable remote reserve-keyword  placeholder="请输入课程名称" 
                                >
                        <el-option v-for="item in newArr" :key="item.title" :label="item.title" :value="item.courseId">
                          </el-option>
                      </el-select>
                  </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogCreateFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="addRelation('createForm')">确 定</el-button>
      </div>
    </el-dialog>
  </section>
</template>
<style>
</style>

<script>
import btns from "@/components/btns.vue";
import breadcrumbs from "@/components/breadcrumbs.vue";
export default {
  components: {
    btns,
    breadcrumbs,
  },
  data() {
    return {
      importFileUrl: this.GLOBAL.imgBaseUrl,
      currentPage: 1,
      pageSize: 10,
      loading: false,
      total: 0,
      formType: "add",
      tableData: [],
      id: null,
      createForm: {},
      options: [],
      dialogCreateFormVisible: false,
      hasFile: false,
      tableSelection: [],
      headImgUrl: "",
      TypeList: [{
        id: 2,
        label: "视频"
      },
      {
        id: 3,
        label: "课件"
      },
      ],
      rules: {
        outCourseId: [{
          required: true,
          message: "请选择需要关联的课程",
          trigger: "change"
        },
          // { validator: allNumValidate, trigger: 'blur' }
        ],
        contentUrl: [{
          required: true,
          message: "请上传课程内容",
          trigger: "change"
        },
          // { validator: allNumValidate, trigger: 'blur' }
        ],

        videoNum: [{
          required: true,
          message: "请输入课程视频时长",
          trigger: "blur"
        },
          // { validator: allNumValidate, trigger: 'blur' }
        ],
        Sort: [{
          required: true,
          message: "请输入排序序号",
          trigger: "blur"
        },
          // { validator: allNumValidate, trigger: 'blur' }
        ],
        title: [{
          required: true,
          message: "请输入课程内容标题",
          trigger: "blur"
        },
          // { validator: allNumValidate, trigger: 'blur' }
        ],
        Type: [{
          required: true,
          message: "请选择课程内容类型",
          trigger: "change"
        },
          // { validator: allNumValidate, trigger: 'blur' }
        ],

      },
      newArr:[]
    };
  },

  created() {
    this.id = this.$route.query.id;
    console.log(this.id)
    this.getList(this.id);
    this.remoteMethod();
  },
  methods: {
    //删除数据
    del() {
      if (this.tableSelection.length < 1) {
        this.$message.error('请选中一行数据');
        return
      }
      this.$confirm("确认要删除这条课程关联, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(() => {
          let ids=this.tableSelection.map(e=>{
            return e.aboutId
          })
          this.$api.course
            .delCourseAbout({
              aboutIds: ids.join(','),
            })
            .then((d) => {
              if (d.code == 200) {
                this.$message({
                  type: "success",
                  message: "删除成功",
                });
                this.getList(this.id);
              } else {
                this.$message.error(d.msg);
              }
            });
        })
        .catch(() => {
          this.$message.info("已取消启用");
        });
    },
    remoteMethod() {
      // if (query !== '') {
        this.loading = true;
        this.$api.course
          .getCourseList({
            // current: 1,
            // size: 20,
            beginTime: '',
            endTime: '',
            keyword: '',
          })
          .then((d) => {
            this.loading = false;
            this.options = d.data;
            this.getNewArr();
          })
          .catch((e) => {
            console.log(e);
          });
      // }
      //  else {
      //   this.options = [];
      // }
    },
    addRelation(formName) {
      // console.log(this.createForm, "1------------------")
      this.$refs[formName].validate((valid) => {
        if (valid) {
          if (this.formType == "add") {
            let row = this.createForm;
            console.log(row, "1---------------------------------")
            this.$api.course.addCourseAbout({
              courseId: this.id,
              outCourseId: row.outCourseId.join(",")
            }).then((res) => {
              if (res.code == 200) {
                this.createForm = {},
                  this.headImgUrl = "",
                  this.hasFile = false;
                this.dialogCreateFormVisible = false;
                this.$message.success("添加成功")
                this.getList(this.id)
              }else{
                this.$message.error(res.msg)
              }
            })
          } else {
            let row = this.createForm;
            this.$api.course.editCourseContent({
              contentId: row.contentId,
              content: row.contentUrl,
              courseId: this.id,
              duration: row.videoNum * 1000,
              headImg: row.headImgUrl,
              sort: row.Sort,
              title: row.title,
              type: row.Type
            }).then((res) => {
              if (res.code == 200) {
                this.createForm = {},
                  this.headImgUrl = "",
                  this.hasFile = false;
                this.dialogCreateFormVisible = false;
                this.$message.success("修改成功")
                this.getList(this.id)
              }
            })
          }

        }
      })
    },
    beforeAvatarUpload() { },
    getUrl(data) {
      console.log(data);
      this.createForm.contentUrl = data;
    },
    getHeadImgUrl(data) {
      this.hasFile = true;
      this.headImgUrl = data;
      this.createForm.headImgUrl = data;
    },
    beforeRemove() { },
    handleRemove() { },
    handlePreview() { },
    handleExceed() { },
    showCourseContentForm(index) {
      if (index == 1) {
        if(this.newArr.length==0){
          return this.$message.warning('已关联所有课程')
        }else{
          this.dialogCreateFormVisible = true;
        }
      } else {
        console.log(this.tableSelection[0].title, "1---------")
        this.formType = "edit"
        this.createForm = {
          outCourseId: this.tableSelection[0]
        }
        if (this.tableSelection.length != 1) {
          this.$message.error('请选中一行数据');
          return
        }
        var demo = this.tableSelection[0];
        console.log(demo);

        // contentId: row.contentId,
        //       content: row.contentUrl,
        //       courseId: this.id,
        //       duration: row.videoNum * 1000,
        //       headImg: row.headImgUrl,
        //       sort: row.Sort,
        //       title: row.title,
        //       type: row.Type
        this.createForm = {
          contentUrl: demo.content,
          videoNum: demo.duration / 1000,
          Sort: demo.sort,
          title: demo.title,
          Type: demo.type,
          contentId: demo.contentId,
          headImgUrl: demo.headImg,

        }
        this.dialogCreateFormVisible = true;
      }

    },
    returnCourseList() {
      this.$router.push("/class/list")
    },
    tableSelectionChange(val) {
      this.tableSelection = val;
    },
    handleSizeChange(val) {
      this.pageSize = val;
      this.getList(this.currentPage, val);
      // eslint-disable-next-line no-console
      // console.log(`每页 ${val} 条`);
    },
    handleCurrentChange(val) {
      this.currentPage = val;
      this.getList(val, this.pageSize);
      // eslint-disable-next-line no-console
      // console.log(`当前页: ${val}`);
    },

    getList(id) {
      this.$api.course.getCourseAboutList({
        courseId: id
      })
        .then((d) => {
          if (d.code == 200) {
            this.tableData = d.data;
            this.total = d.totalCount;
            this.getNewArr();
          }
        });
    },
    getNewArr(){
      var newArr = []
      this.options.forEach(element => {
        if(this.tableData.findIndex(o=>{
          return o.courseId==element.courseId
        })==-1){
          newArr.push(element)
        }
      });
      this.newArr=newArr
    }
  },

};
</script>
<style lang="less" scoped>
.flex {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
.img-feng {
  width: 120px;
  height: 120px;
}
</style>
